package com.hinacom.pix.web.interceptor;

import com.alibaba.fastjson.JSON;
import com.hinacom.pix.web.annotation.ResponseJson;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by fyu on 2016/9/23.
 */
public class JsonHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) o;
        Method method = handlerMethod.getMethod();
        ResponseJson responseJson = method.getAnnotation(ResponseJson.class);


        // Json 输出
        if (responseJson != null) {
            // 获取Model
            Map map = modelAndView.getModel();

            // HashMap<String, Object> newMap = new HashMap<String, Object>();
            // remove the spring object, only remain the user objects
            for (Object key : map.keySet()) {
                Object object = map.get(key);
                if (object instanceof org.springframework.validation.BindingResult) {
                    map.remove(key);
                }
            }

            String json = JSON.toJSONString(map);;
            try {
                httpServletResponse.setContentType("text/html; charset=gbk");
                httpServletResponse.getWriter().print(json);
                httpServletResponse.getWriter().close();
            } catch (Exception ex) {

            } finally {

            }
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
